package com.shwread.android.qysw.activity.task;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.GlideUtil;
import com.NewActionHelp;
import com.ciko.code.views.MyListView;
import com.ciko.code.views.multi_image_selector.MultiImageSelectorActivity;
import com.google.gson.reflect.TypeToken;
import com.image_see.ImageSeeActivity;
import com.shwread.android.qysw.QyReaderApp;
import com.shwread.android.qysw.bean.que.OptionBean;
import com.shwread.android.qysw.bean.que.QueInfo;
import com.shwread.android.qysw10000000.R;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.io.FileNotFoundException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import logic.util.Util;

/**
 * 题目
 */
public class QuestionItemFragment extends Fragment implements OptionsListAdapter.UpListener {
    private static final String QUE_INDEX = "queIndex";
    private static final String QUE_IS_FINISH = "queIsFinish";
    private static final String QUE_INFO = "queInfo";
    private static final int REQUEST_IMAGE = 7;

    private Activity activity;
    /**
     * 选择的图片路径存储
     */
    private ArrayList<String> selectedPictureAll = new ArrayList<>();

    /**
     * 题目标题
     */
    private TextView tvQueTitle;
    /**
     * 答题数/总数
     */
    private TextView tvQueCursor;
    /**
     * 填空
     */
    private EditText etQueTypeThree;
    /**
     * 上传凭证
     */
    private ImageView imgQueTypeFour;
    /**
     * 选项列表
     */
    private MyListView lvOptions;
    /**
     * 题目对象
     */
    private QueInfo queInfo;

    /**
     * 当前所在的题目位置
     */
    private int index;
    private boolean isFinish;
    private OptionsListAdapter adapter;
    /**
     * 答案对象
     */
    private OptionBean queItemBean;
    private int maxLength;

    public static QuestionItemFragment newInstance(int index, boolean isFinish, QueInfo dataInfo) {
        QuestionItemFragment fragment = new QuestionItemFragment();
        Bundle args = new Bundle();
        args.putInt(QUE_INDEX, index);
        args.putBoolean(QUE_IS_FINISH, isFinish);
        args.putSerializable(QUE_INFO, dataInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            index = bundle.getInt(QUE_INDEX);
            isFinish = bundle.getBoolean(QUE_IS_FINISH);
            queInfo = (QueInfo) bundle.getSerializable(QUE_INFO);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View customView = inflater.inflate(R.layout.fragment_question, container, false);
        queItemBean = QuestionnaireDetailActivity.QueList.get(index);
        initView(customView);
        tvQueCursor.setText(Html.fromHtml("<big><big>" + (index + 1) + "</big></big>" + "/" + QuestionnaireDetailActivity.QueList.size()));
        String type = queInfo.getItemType();
        itemIsShow(type);
        optionShow(type);

        lvOptions.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//条目点击事件
                adapter.notifyDataSetChanged();
                String itemId = "";
                for (int i = 0; i < queInfo.getQuestionnaireItemOptionInfos().size(); i++) {
                    if (lvOptions.isItemChecked(i)) {
                        itemId += queInfo.getQuestionnaireItemOptionInfos().get(i).getId() + ",";
                    }
                }
                if (TextUtils.isEmpty(itemId)) {
                    queItemBean.setOptionId("");//置空
                    queItemBean.setFinish(false);
                } else {
                    queItemBean.setOptionId(itemId.substring(0, itemId.length() - 1));
                    queItemBean.setFinish(true);
                }

            }
        });
        return customView;
    }

    /**
     * 加载选项数据
     * @param type 题目类型
     */
    private void optionShow(String type) {
        switch (type) {//1=单选 2=多选 3=是非 4=填空 5=文件 String
            case "1": {//单选
                tvQueTitle.setText(String.format("%s(%s)", queInfo.getTitle(),"单选题"));
                adapter = new OptionsListAdapter(queInfo.getQuestionnaireItemOptionInfos(), isFinish, this);
                lvOptions.setAdapter(adapter);
                lvOptions.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

                String itemId = queItemBean.getOptionId();
                if (!TextUtils.isEmpty(itemId)) {
                    for (int i = 0; i < queInfo.getQuestionnaireItemOptionInfos().size(); i++) {
                        String id = String.valueOf(queInfo.getQuestionnaireItemOptionInfos().get(i).getId());
                        if (itemId.equals(id)) {
                            lvOptions.setItemChecked(i, true);
                        }
                    }
                }
                break;
            }
            case "2": {//多选
                tvQueTitle.setText(String.format("%s(%s)", queInfo.getTitle(),"多选题"));
                adapter = new OptionsListAdapter(queInfo.getQuestionnaireItemOptionInfos(), isFinish, this);
                lvOptions.setAdapter(adapter);
                lvOptions.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                String itemId = queItemBean.getOptionId();
                if (!TextUtils.isEmpty(itemId)) {
                    String[] itemIdList = itemId.split(",");

                    for (int i = 0; i < queInfo.getQuestionnaireItemOptionInfos().size(); i++) {
                        String id = String.valueOf(queInfo.getQuestionnaireItemOptionInfos().get(i).getId());
                        for (String s : itemIdList) {
                            if (s.equals(id)) {
                                lvOptions.setItemChecked(i, true);
                            }
                        }
                    }
                }
                break;
            }
            case "3": {//判断
                tvQueTitle.setText(Html.fromHtml(String.format("%s(%s)", queInfo.getTitle(),"判断题")));
                adapter = new OptionsListAdapter(queInfo.getQuestionnaireItemOptionInfos(), isFinish, this);
                lvOptions.setAdapter(adapter);
                lvOptions.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                String itemId = queItemBean.getOptionId();
                if (!TextUtils.isEmpty(itemId)) {
                    for (int i = 0; i < queInfo.getQuestionnaireItemOptionInfos().size(); i++) {
                        String id = String.valueOf(queInfo.getQuestionnaireItemOptionInfos().get(i).getId());
                        if (itemId.equals(id)) {
                            lvOptions.setItemChecked(i, true);
                        }
                    }
                }
                break;
            }
            case "4": {//填空题
                maxLength = queInfo.getMaxLength();
                etQueTypeThree.setHint(String.format("请输入,%s字以内", maxLength));
                tvQueTitle.setText(String.format("%s(%s)", queInfo.getTitle(), "填空题"));

                etQueTypeThree.setText(queItemBean.getAnswerContent());
                if (isFinish) {//已完成禁止点击
                    etQueTypeThree.setKeyListener(null);
                }
                //填空题监听
                etQueTypeThree.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (s.length() <= 0) {
                            queItemBean.setFinish(false);
                        } else if (s.length() > maxLength) {
                            Util.showToast(QyReaderApp.application, "超过了字数限制");
                            CharSequence sequence = s.subSequence(0,maxLength);
                            etQueTypeThree.setText(sequence);
                            etQueTypeThree.setSelection(sequence.length());
                            queItemBean.setAnswerContent(sequence.toString());
                            queItemBean.setFinish(true);
                        } else {
                            queItemBean.setAnswerContent(s.toString());
                            queItemBean.setFinish(true);
                        }
                    }
                });
                break;
            }
            case "5": {//上传凭证
                if (!TextUtils.isEmpty(queItemBean.getAnswerContent())) {
                    GlideUtil.load(activity, queItemBean.getAnswerContent(), imgQueTypeFour);
                }
                tvQueTitle.setText(String.format("%s(%s)", queInfo.getTitle(), "上传凭证"));
                imgQueTypeFour.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        selectorImg();
                    }
                });
                break;
            }
        }
    }

    private void selectorImg() {
        if (isFinish) {//查看图片
            Intent intent = new Intent( activity, ImageSeeActivity.class);
            ArrayList<String> urlList = new ArrayList<>();
            urlList.add(queItemBean.getAnswerContent());
            intent.putStringArrayListExtra("urlList", urlList);
            startActivity(intent);
        } else {//选择图片
        Intent intent = new Intent(activity, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        // 默认选择
        if (selectedPictureAll != null && selectedPictureAll.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
        }
    }

    private void initView(View customView) {
        tvQueCursor = (TextView) customView.findViewById(R.id.tv_que_cursor);
        tvQueTitle = (TextView) customView.findViewById(R.id.tv_que_title);
        lvOptions = (MyListView) customView.findViewById(R.id.lv_options);
        etQueTypeThree = (EditText) customView.findViewById(R.id.et_que_type_three);
        imgQueTypeFour = (ImageView) customView.findViewById(R.id.img_que_type_four);
    }

    /**
     * 控制选项的显示和隐藏
     *
     * @param type Item类型
     */
    void itemIsShow(String type) {
        lvOptions.setVisibility("1".equals(type) || "2".equals(type) || "3".equals(type) ? View.VISIBLE : View.GONE);
        etQueTypeThree.setVisibility("4".equals(type) ? View.VISIBLE : View.GONE);
        imgQueTypeFour.setVisibility("5".equals(type) ? View.VISIBLE : View.GONE);
    }

    @Override
    public void updateBackground(int position, View view) {
        if ("2".equals(queInfo.getItemType())) {
            if (lvOptions.isItemChecked(position)) {
                view.setBackgroundResource(R.drawable.img_checked);
            } else {
                view.setBackgroundResource(R.drawable.img_unchecked);
            }
        } else {
            if (lvOptions.isItemChecked(position)) {
                view.setBackgroundResource(R.drawable.item_ring_oval);
            } else {
                view.setBackgroundResource(R.drawable.item_ring);
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE && data != null) {//选择图片回调
            ArrayList<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            selectedPictureAll.addAll(mSelectPath);
            for (String path : mSelectPath) {
                Log.e("sss", "图片地址---" + path);
                GlideUtil.loadLocalUrl(activity, path, imgQueTypeFour, null);
                try {
                    upFile(path);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    Util.showToast(QyReaderApp.application, "上传凭证失败,请重新选择凭证进行上传");
                }
            }
        }
    }

    /**
     * 上传文件
     *
     * @param path 文件路径
     */
    private void upFile(String path) throws FileNotFoundException {
        NewActionHelp.uploadQuestionnaireFile(activity, path, new ObjectHttpResponseHandler<HashMap<String, String>>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("sss", "失败--" + s);
                Util.showToast(QyReaderApp.application, "上传凭证失败,请重新选择凭证进行上传");
            }

            @Override
            public void onSuccess(int i, Header[] headers, HashMap<String, String> map, String s) {
                Log.e("sss", "成功--" + s);
                String url = map.get("fileUrl");
                queItemBean.setAnswerContent(url);
                queItemBean.setFinish(true);
                queItemBean.setFileType("1");
            }

            @Override
            public Type getType() {
                return new TypeToken<HashMap<String, String>>() {
                }.getType();
            }
        });
    }
}
